import React from 'react';
import { Tree, Icon, Spin } from 'antd';
import { Menu, Item, MenuProvider, Separator, contextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.min.css';

let disabled = false;
const { TreeNode } = Tree;

const TreeWithContextMenu = ({ dataSource, onSelect, contextMenus, onHandle, fixdMenu }) => {
  // 上下文菜单
  const ContextMenu = () => (
    // eslint-disable-next-line no-use-before-define
    <Menu id="extrastu" style={{ width: 100, minWidth: 100 }}>
      {contextMenus.map(menu => {
        return (
          <Item onClick={onHandle} data={menu}>
            <span>
              <Icon type={menu.icon} style={{ marginRight: 5 }} />
              {menu.name}
            </span>
          </Item>
        );
      })}
    </Menu>
  );

  // 渲染树节点，主要目的是为了通过react-contexify包裹上下文菜单
  const renderEntityTreeNodes = data => {
    return data.map(item => {
      const title = (
        <span style={{ display: 'inline-block' }}>
          <MenuProvider data={item} id="extrastu">
            <span style={{ padding: 5 }}>{item.text}</span>
          </MenuProvider>
        </span>
      );

      if (item.children) {
        if (item.data.disabled) {
          return (
            <TreeNode
              {...item}
              key={item.id}
              title={title}
              data={item.data}
              isShared={item.isShared}
              className="disabledClass"
              value={item.id}
              icon={<Icon type="stop" style={{ color: '#c6c6c6' }} />}
            >
              {renderEntityTreeNodes(item.children)}
            </TreeNode>
          );
        }
        return (
          <TreeNode
            {...item}
            key={item.id}
            title={title}
            data={item.data}
            isShared={item.isShared}
            value={item.id}
          >
            {renderEntityTreeNodes(item.children)}
          </TreeNode>
        );
      }

      return (
        <TreeNode
          {...item}
          key={item.id}
          title={title}
          data={item.data}
          isShared={item.isShared}
          value={item.id}
        />
      );
    });
  };

  function handleEvent(e, item) {
    e.preventDefault();
    if (item.data.disabled) {
      // eslint-disable-next-line no-param-reassign
      contextMenus = contextMenus.filter(val => val.key != 'off');
    } else {
      // eslint-disable-next-line no-param-reassign
      contextMenus = contextMenus.filter(val => val.key != 'on');
    }

    // fixdMenu(contextMenus);
    contextMenu.show({
      id: 'extrastu',
      event: e,
    });
  }

  return (
    <div>
      {dataSource.length ? (
        <Tree showIcon showLine defaultExpandAll onSelect={onSelect} defaultExpandedKeys={['root']}>
          {renderEntityTreeNodes(dataSource)}
        </Tree>
      ) : (
        <Spin />
      )}
      <ContextMenu />
    </div>
  );
};

export default TreeWithContextMenu;
